package com.dream.service.recommender.hub.rec;

import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.service.procure.domain.enums.StockStatus;
import com.dream.service.product.domain.entity.SpuBase;
import com.dream.service.recommender.hub.util.CacheUtil;
import com.dream.service.recommender.hub.util.ParamUtil;
import com.dream.service.recommender.base.compare.WeightComparator;
import com.dream.service.recommender.base.impl.BaseRecommenderService;
import com.dream.service.recommender.domain.request.BaseRequest;
import com.dream.service.recommender.domain.request.FrontParam;
import com.dream.service.recommender.domain.response.RecommenderData;
import com.dream.service.recommender.domain.response.RecommenderItem;
import com.dream.service.recommender.domain.response.RecommenderSku;
import com.dream.service.recommender.toolkits.cache.RedisCache;
import com.dream.service.recommender.toolkits.utils.StringUtils;
import com.dream.service.search.api.SearchRecallService;
import com.dream.service.search.domain.entity.ProductRecallResult;
import com.dream.service.search.domain.request.ProductSearchRequest;
import com.dream.service.wrapper.domain.entity.SPUData;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 根据分类召回
 * Created by zhiji on 2016/04/25.
 */
public class CategoryListPDRecommender extends BaseRecommenderService {

    private SearchRecallService searchRecallService;

    public SearchRecallService getSearchRecallService() {
        return searchRecallService;
    }

    private Logger logger = Logger.getLogger(CategoryListPDRecommender.class);

    @Autowired
    public void setSearchRecallService(SearchRecallService searchRecallService) {
        this.searchRecallService = searchRecallService;
    }

    // 获取商品数据倍数
    private int multiple = 5;

    // 失效时间间隔 (sec)
    private int residue_time_interval = 10 * 60;

    // 缓存
    private final String existCacheKey = "rec_category_list_";
    private final String imprCacheKey = "rec_category_list_impr_";

    // 缓存
    private RedisCache redisCache = RedisCache.getInstance();

    @Override
    public BaseResponse<RecommenderData> getRecommender(BaseRequest<FrontParam> frontParamBaseRequest) {
        long sTime = System.currentTimeMillis();
        BaseResponse<RecommenderData> recommenderResponse = new BaseResponse<RecommenderData>();
        try {
            if (frontParamBaseRequest == null || frontParamBaseRequest.getParam() == null || frontParamBaseRequest.getParam().getUser() == null) {
                return buildResult(recommenderResponse, false, ErrorCode.PARAM_ERROR.getCode(), ErrorCode.PARAM_ERROR.getError_msg(), null);
            }
            FrontParam frontParam = frontParamBaseRequest.getParam();
            int cid = ParamUtil.getCid(frontParam);
            int pagesize = ParamUtil.getPageSize(frontParam);
            int page = ParamUtil.getPage(frontParam);
            Map<Integer, Double> categoryWeightMap = new HashMap<Integer, Double>();
            if (cid > 0) {
                categoryWeightMap.put(cid, 1d);
            }
            /*int skip = pagesize * (page - 1);*/
            //已经展示sku集合
            String pin = ParamUtil.getPin(frontParam);
            String uuid = ParamUtil.getUUid(frontParam);

            Set<Long> existSpus = gatherExistSpuInfo(pin, uuid, cid, page, pagesize);
            Set<Long> imprSpus = gatherImprSpuInfo(pin, uuid, cid);
            List<ProductRecallResult> recallResults =gatherSearchRecallData(categoryWeightMap, null, pagesize * multiple,existSpus, 0);

            Integer cityId = frontParam.getCityId();
            RecommenderData recommenderData = buildResult(recallResults, cid,existSpus,imprSpus,page,cityId);

            recommenderResponse = buildResult(recommenderResponse, true, ErrorCode.OK.getCode(), "", recommenderData, 0, pagesize);

            Set<Long> spus = rebuildPositionInfo(recommenderResponse.getResult());

//            System.out.println("curspus:::"+spus);
            backupExistAndImprSpuInfo(pin, uuid, spus, cid);

            long usedTime = System.currentTimeMillis() - sTime;
            recommenderData.setLatency(usedTime);
            recommenderResponse.setLatency(usedTime);
            return recommenderResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return buildResult(recommenderResponse, false, ErrorCode.PROCESS_ERROR.getCode(), e.getMessage(), null);
        }
    }

    /**
     * 更新位置信息
     * @param recommenderData
     * @return
     */
    public Set<Long> rebuildPositionInfo(RecommenderData recommenderData) {
        if (recommenderData == null || StringUtils.isEmpty(recommenderData.getList())) {
            return null;
        }
        List<RecommenderItem> items = recommenderData.getList();
        Set<Long> spus = new HashSet<Long>();
        int pos = 1;
        for (RecommenderItem recommenderItem : items) {
            recommenderItem.setPos(pos++);
            if (recommenderItem instanceof RecommenderSku) {
                try {
                    spus.add(((RecommenderSku) recommenderItem).getSpu());
                } catch (Exception e) {}
            }
        }
        return spus;
    }

    public Set<Long> gatherExistSpuInfo(String pin, String uuid, int category, int pageNum, int pageSize) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) {
            return Collections.emptySet();
        }
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
        String key = existCacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));
        if (pageNum == 1) {
            redisCache.delKey(key.getBytes());
            return Collections.emptySet();
        }
        Set<Long> spus = CacheUtil.getExistSpus(redisCache, key, (pageNum - 1) * pageSize);
        if (spus == null) {
            return Collections.emptySet();
        }
        return spus;
    }


    public Set<Long> gatherImprSpuInfo(String pin, String uuid, int category) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) {
            return Collections.emptySet();
        }
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
        String key = imprCacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));

        Set<Long> spus = CacheUtil.getImprSpus(redisCache, key);
        if (spus == null) {
            return Collections.emptySet();
        }
        return spus;


    }


    private List<ProductRecallResult> gatherSearchRecallData(Map<Integer, Double> categoryWeightMap, Map<Integer, Double> labelWeightMap, int limit, Set<Long> existSpus, int skip) {
        ProductSearchRequest request = new ProductSearchRequest();
        if (categoryWeightMap != null && !categoryWeightMap.isEmpty()) {
            request.setFrontCategoryWeightMap(categoryWeightMap);
        }
        if (labelWeightMap != null && !labelWeightMap.isEmpty()) {
            request.setLabelWeightMap(labelWeightMap);
        }
        request.setLimit(limit);
        request.setSkip(skip);
        if (existSpus != null && !existSpus.isEmpty()) {
            request.setExistKeys(existSpus);
        }
        try {
            if (searchRecallService == null) {
                return null;
            }
            BaseResponse<List<ProductRecallResult>> recallResponse = searchRecallService.productSearchRecall(request);
            if (recallResponse.isSuccess()) {
                return recallResponse.getResult();
            }
        } catch (Exception e) {
        }
        return null;
    }

    public void backupExistAndImprSpuInfo(String pin, String uuid, Set<Long> spus, int category) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) return;
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;

        String key = existCacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));
        List<Long> existCache = CacheUtil.backupCache(redisCache, key, spus, residue_time_interval, -1);
//        System.out.println("Backup Exist Spu :" + (existCache == null ? "" : Arrays.toString(existCache.toArray())));

        String keyImpr = imprCacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));
        List<Long> imprCache = CacheUtil.backupCache(redisCache, keyImpr, spus, residue_time_interval, -1);
//        System.out.println("Backup Impr Spu :" + (imprCache == null ? "" : Arrays.toString(imprCache.toArray())));

    }

    /**
     * 封装结果
     * @param recallResults
     * @param category
     * @return
     */
    private RecommenderData buildResult(List<ProductRecallResult> recallResults, int category,Set<Long> existSpus,Set<Long> imprSpus,int page ,Integer cityId) {
        if (StringUtils.isEmpty(recallResults)) {
            return new RecommenderData();
        }
        RecommenderData<RecommenderSku> recommenderData = new RecommenderData<RecommenderSku>();
        List<RecommenderSku> recommenderSkus = new ArrayList<RecommenderSku>();
        recommenderData.setList(recommenderSkus);
        Set<Long> spus = new HashSet<Long>();
        for (ProductRecallResult recallResult : recallResults) {
            spus.add(recallResult.getSpu());
        }
        Map<Long, SPUData> spuDataMap = getBaseInfo(spus,cityId);
        if (spuDataMap == null || spuDataMap.isEmpty()) {
            return recommenderData;
        }
        for (ProductRecallResult recallResult : recallResults) {
            RecommenderSku recommenderSku = buildProduct(recallResult, spuDataMap.get(recallResult.getSpu()));
            if (recommenderSku != null) {
                recommenderSkus.add(recommenderSku);
            }
        }
        if(page==1)
            SortAndRankPD(recommenderData, spuDataMap, imprSpus);
        else
            SortAndRank(recommenderData, spuDataMap);
        return recommenderData;
    }

    /**
     * 封装商品信息
     * @param recallResult
     * @param spuData
     * @return
     */
    private RecommenderSku buildProduct(ProductRecallResult recallResult, SPUData spuData) {
        if (recallResult == null || spuData == null || spuData.getSpuBase() == null  || spuData.getStockStatus() != StockStatus.YES) {
            return null;
        }
        RecommenderSku recommenderSku = new RecommenderSku();
        SpuBase spuBase = spuData.getSpuBase();
        recommenderSku.setSpu(spuBase.getSpu());
        recommenderSku.setMain_sku(spuBase.getMain_sku());
        recommenderSku.setMain_title(spuBase.getMain_title());
        recommenderSku.setW(recallResult.getQuality_score());
        if (recallResult !=null && recallResult.getOther_image_paths() != null) {
            recommenderSku.setImage_paths(recallResult.getOther_image_paths());
        }
        if (!StringUtils.isEmpty(spuBase.getMain_image_url())) {
            recommenderSku.setMain_image_url(spuBase.getMain_image_url());
        }
        if (spuData.getSkuPrice() != null) {
            recommenderSku.setSkuPrice(spuData.getSkuPrice());
        }
        return recommenderSku;
    }


    /**
     * 穿插排序 (通过类目穿插)
     * @param recommenderData
     * @param spuDataMap
     * @return
     */
    public RecommenderData SortAndRankPD(RecommenderData recommenderData, Map<Long, SPUData> spuDataMap,Set<Long> imprSpu) {
        if (recommenderData == null) {
            return recommenderData;
        }
//        System.out.println(imprSpu);
        List<RecommenderSku> recommenderSkus = recommenderData.getList();
        if (StringUtils.isEmpty(recommenderSkus)) {
            return recommenderData;
        }
        Map<Integer, List<RecommenderSku>> categoryItems = new HashMap<Integer, List<RecommenderSku>>();
        for (RecommenderSku recommenderSku : recommenderSkus) {//根据cid重组spu
            long spu = recommenderSku.getSpu();
            SPUData spuData = spuDataMap.get(spu);
            if (spuData == null) {//是不是多余的判断?
                continue;
            }
            SpuBase spuBase = spuData.getSpuBase();
            List<RecommenderSku> relSkus = categoryItems.get(spuBase.getCategory_id());
//            System.out.println(JSONObject.toJSONString(spuBase));
//            System.out.println(spuBase.getCategory_id());
//            System.out.println(spuBase.getFront_category_ids());
            if (relSkus == null) {
                relSkus = new ArrayList<RecommenderSku>();
                categoryItems.put(spuBase.getCategory_id(), relSkus);
            }
            relSkus.add(recommenderSku);
        }
        List<RecommenderSku> sortRecommenderItems = new ArrayList<RecommenderSku>();
        boolean loop = true;
        do {
            List<RecommenderSku> subRecommenderItems = new ArrayList<RecommenderSku>(categoryItems.size());

            Iterator<Map.Entry<Integer, List<RecommenderSku>>> entryiterator = categoryItems.entrySet().iterator();
            while (entryiterator.hasNext()) {
                Map.Entry<Integer, List<RecommenderSku>> productentry = entryiterator.next();
                List<RecommenderSku> productList = productentry.getValue();
                if (StringUtils.isEmpty(productList)) {
                    entryiterator.remove();
                    continue;
                }
                RecommenderSku recommenderSku = productList.remove(0);
                recommenderSku.setW(Math.random());
                if(imprSpu.contains(recommenderSku.getSpu()))//对于已存在的spu降权0.5
                {
//                    System.out.println(recommenderSku.getSpu()+"降权");
                    recommenderSku.setW(recommenderSku.getW()-1);
                }
                subRecommenderItems.add(recommenderSku);
//                System.out.println("cur W:::"+recommenderSku.getSpu()+"=="+recommenderSku.getW());
            }
            Collections.sort(subRecommenderItems, new WeightComparator());
            sortRecommenderItems.addAll(subRecommenderItems);
            if (categoryItems.isEmpty()) {
                loop = false;
            }
            if (categoryItems.size() == 1) {
                Set<Integer> keys = categoryItems.keySet();
                Iterator<Integer> keyiterator = keys.iterator();
                while (keyiterator.hasNext()) {
                    Integer catid = keyiterator.next();
                    sortRecommenderItems.addAll(categoryItems.get(catid));
                }
                loop = false;
            }
        } while (loop);
        recommenderData.setList(sortRecommenderItems);
        return recommenderData;
    }
}
